package controllers

import (
	"git.oschina.net/antlinker/antevent/server/app"
	"git.oschina.net/antlinker/antevent/server/bus"
	"github.com/goadesign/goa"
)

// AnalysisController implements the analysis resource.
type AnalysisController struct {
	*goa.Controller
	listener bus.Analysis
}

// NewAnalysisController creates a analysis controller.
func NewAnalysisController(service *goa.Service, abus *bus.AllBus) *AnalysisController {
	return &AnalysisController{Controller: service.NewController("AnalysisController"), listener: abus.Analysis()}
}

// Hook runs the hook action.
func (c *AnalysisController) Hook(ctx *app.HookAnalysisContext) error {
	eid := ctx.Eid
	if eid == "" {
		msg := "参数错误,没有设置eid"

		return ctx.BadRequest(&app.AntError{
			Msg: &msg,
		})
	}
	// AnalysisController_Hook: start_implement

	// Put your logic here
	res, err := c.listener.QueryHook(eid)

	// AnalysisController_List: end_implement
	if err != nil {
		msg := err.Error()
		r := &app.AntError{Msg: &msg}
		return ctx.InternalServerError(r)
	}
	return ctx.OK(res)
}

// List runs the list action.
func (c *AnalysisController) List(ctx *app.ListAnalysisContext) error {
	// AnalysisController_List: start_implement

	// Put your logic here
	var (
		etype  = ""
		action = ""
		from   = ""
		page   = 1
		count  = 10
	)

	if ctx.Etype != nil {
		etype = *ctx.Etype
	}
	if ctx.Action != nil {
		action = *ctx.Action
	}
	if ctx.From != nil {
		from = *ctx.From
	}
	if ctx.Page != nil {
		page = *ctx.Page
		if page < 0 {
			page = 1
		}
	}
	if ctx.Count != nil {
		count = *ctx.Count
		if count < 0 {
			count = 10
		}
		if count > 100 {
			count = 100
		}
	}

	res, err := c.listener.QueryEvent(etype, action, from, page, count)

	// AnalysisController_List: end_implement
	if err != nil {
		msg := err.Error()
		r := &app.AntError{Msg: &msg}
		return ctx.InternalServerError(r)
	}
	goa.LogInfo(ctx, "查询结果:%#v", res)
	return ctx.OK(&res)
}
